cmake_minimum_required(VERSION 3.22)

ExternalProject_Add(external_leveldb
  URL https://github.com/google/leveldb/archive/refs/tags/1.23.tar.gz
  URL_HASH MD5=afbde776fb8760312009963f09a586c7
  DOWNLOAD_NO_PROGRESS 0
  UPDATE_COMMAND ""
  LOG_CONFIGURE 1
  LOG_BUILD 1
  LOG_INSTALL 1
  BUILD_ALWAYS 1
  CMAKE_ARGS
    -DCMAKE_PREFIX_PATH=${STAGED_INSTALL_PREFIX}
    -DCMAKE_INSTALL_PREFIX=${STAGED_INSTALL_PREFIX}
    -DCMAKE_BUILD_TYPE=${LIB_BUILD_TYPE}
    -DBUILD_STATIC_LIBS=ON
    -DBUILD_SHARED_LIBS=OFF
    -DLEVELDB_BUILD_TESTS=OFF
    -DLEVELDB_BUILD_BENCHMARKS=OFF
  BUILD_COMMAND make -j${CPU_CORE}
)

set(PROTO_SOURCE kvstore.proto)
execute_process(COMMAND ${PROTOBUF_PROTOC} 
  -I${CMAKE_CURRENT_SOURCE_DIR} 
  --cpp_out=${CMAKE_CURRENT_SOURCE_DIR} 
  ${PROTO_SOURCE}
)

set(FILE_NAME_PREFIX kv_)
file(GLOB PROTO_SRC "${CMAKE_CURRENT_SOURCE_DIR}/*.pb.cc")

foreach(SRV_OR_CLT server client)
  set(TARGET_NAME "")
  set(EXAMPLE_SOURCES "")
  string(APPEND TARGET_NAME ${FILE_NAME_PREFIX} ${SRV_OR_CLT})
  string(APPEND EXAMPLE_SOURCES ${TARGET_NAME} ".cpp")
  add_executable(${TARGET_NAME} ${EXAMPLE_SOURCES} ${PROTO_SRC})
  target_link_directories(${TARGET_NAME}
    PRIVATE ${STAGED_INSTALL_PREFIX}/lib
  )
  target_link_libraries(${TARGET_NAME}
    PRIVATE rpc
    PRIVATE leveldb
  )
endforeach()